< previous page page_182 next page >

Page 182
Integer division (\)
Modulus arithmetic (Mod)
Addition and subtraction (+, -)
Within a subset of an expression, the components are processed from left to right. When all subset groups have been calculated, the remainder of the expression is calculated from left to right.
In the previous example (4 * 3 + 6 / 2), the multiplication and division portions (4 * 3, which is 12, and 6 / 2, which is 3) would be calculated first, leaving a simpler expression of 12 + 3, for a total of 15.
An important note is that you can override normal operator precedence by using parentheses to group subexpressions that you want to be evaluated first. You can use multiple nested levels of parentheses. Visual Basic calculates subexpressions within parentheses first, innermost set to outermost set, and then applies the normal operator precedence.
CAUTION
Understanding operator precedence is crucial to making sure your programs evaluate expressions the way that you expect. For example, if you want to calculate the average of two test scores, you might write this line of code:
fAvgScore = nTest1 + nTest2 / 2
This line of code might look right, but Visual Basic's calculation won't be correct. Because the division operator has a higher precedence than the addition operator, the subexpression nTest2 / 2 is calculated first and then added to nTest1. This order is obviously incorrect. You can avoid this problem by using parentheses to control the flow of evaluation:
fAvgScore = (nTest1 + nTest2) / 2
This expression will be calculated properly by evaluating the sum of nTest1 + nTest2 first and then dividing the sum by 2. If value of nTest1 is 97 and the value of nTest2 is 85, the expression is evaluated as (97 + 88) / 2, or 185 / 2, which stores the correct result of 92.5 in fAvgScore. Leaving out the parentheses would have resulted in an undesired answer (following the rules of operator precedence) of 97 + 88 / 2, or 97 + 44, or 141.

Visual Basic's Operator Precedence Help screen has a good discussion of the topic, including how the precedence extends to comparison operators and logical operators.
Working with Strings
As you develop your applications, you use strings for many purposes. The better you manipulate the strings that you use, the more professional your programs appear. Visual Basic allows you to be quite flexible as you work with the strings in your programs.

 
< previous page page_182 next page >